/**
 * 
 */
package com.edocbase.desktop.plugins.mdiary.actions;

import java.util.ArrayList;
import java.util.List;

import org.eclipse.draw2d.ActionEvent;
import org.eclipse.draw2d.ActionListener;
import org.eclipse.draw2d.Figure;

import com.edocbase.biz.diary.entities.WebAccount;
import com.edocbase.desktop.maildriver.DesktopApplication;
import com.edocbase.desktop.maildriver.DriverWorker;
import com.edocbase.desktop.plugins.mdairy.part.diary.DiaryWorkPart;
import com.edocbase.desktop.plugins.mdairy.part.diary.SelecteAccountDialog;
import com.edocbase.entity.EntityManager;
import com.edocbase.entity.EntityManagerFactory;
import com.edocbase.entity.StoreException;
import com.edocbase.webdriver.DriverException;

/**
 * @author lifei114@gmail.com
 * 
 */
public class SyncAction implements ActionListener {
	private DiaryWorkPart part = null;

	public SyncAction(DiaryWorkPart diaryWorkPart) {
		part = diaryWorkPart;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.eclipse.draw2d.ActionListener#actionPerformed(org.eclipse.draw2d.
	 * ActionEvent)
	 */
	@Override
	public void actionPerformed(ActionEvent event) {
		String acts[] = DesktopApplication.getPropertyConfig().getStringArray(
				"last.down.account");
		if (acts != null && acts.length > 0) {
			EntityManager<WebAccount> accountManager=EntityManagerFactory
			.getEntityManager(WebAccount.class);
			List<WebAccount> actList = new ArrayList<WebAccount>();
			for (String act:acts){
				try {
					WebAccount webAccount = accountManager.createQuery().EQUALS("fullAccount", act).findOne();
					actList.add(webAccount);
				} catch (StoreException e) {
					e.printStackTrace();
				}
			}
			if (actList.size() > 0){
				sync(actList);
			}
		} else {
			Figure parent = (Figure) event.getSource();
			SelecteAccountDialog dialog = new SelecteAccountDialog(part
					.getViewer().getDesktopShell().getShell(), parent);
			Object obj = dialog.open();
			if (obj != null) {
				List<WebAccount> actList = (List<WebAccount>) obj;
				sync(actList);
			}
		}
	}

	private void sync(List<WebAccount> actList) {
		for (WebAccount account:actList){
			DriverWorker worker = DriverWorker.getWorker();
			try {
				worker.receive(account);
			} catch (DriverException e) {
				e.printStackTrace();
			}
		}
	}
}
